package com.cnwidsom.plugins.persistence;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;

import com.cnwidsom.monitor.MonitorItem;

public class FilePersistence implements Persistence {
	private Map<String, String> params;
	private File file;

	public String getName() {
		return "file";
	}

	public void writeData(MonitorItem mi) {
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(file, true));
			bw = new BufferedWriter(osw);
			bw.write(mi.toJsonString() + "\n");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void setParameters(Map<String, String> params) {
		this.params = params;
		if (params != null && params.get("logFilePath") != null) {
			file = new File(params.get("logFilePath"));
			if (!file.exists()) {
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				try {
					if (!file.createNewFile()) {
						return;
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
		}
	}
}
